from loguru import logger
import asyncio
import tomllib
import os
from datetime import datetime
from random import randint
import json

import aiohttp

from WechatAPI import WechatAPIClient
from utils.decorators import *
from utils.plugin_base import PluginBase


class TestPlugin(PluginBase):
    description = "测试插件"
    author = "测试作者"
    version = "1.0.0"

    def __init__(self):
        super().__init__()
        logger.info("初始化 TestPlugin 插件")

        try:
            with open("plugins/TestPlugin/config.toml", "rb") as f:
                plugin_config = tomllib.load(f)
            config = plugin_config["TestPlugin"]
            self.enable = config["enable"]
            # 获取允许的联系人列表
            self.allowed_contacts = config.get("allowed_contacts", [])
            # 节日提醒相关配置
            self.holiday_reminder = config.get("holiday_reminder", False)
            self.holidays = config.get("holidays", [])
            # 天聚数行API密钥
            self.tianapi_key = config.get("tianapi_key", "")
            # 是否使用API获取节日信息
            self.use_holiday_api = config.get("use_holiday_api", False)
            
            logger.info(f"TestPlugin 插件已加载，启用状态: {self.enable}")
            logger.info(f"允许的联系人数量: {len(self.allowed_contacts)}")
        except Exception as e:
            logger.error(f"加载 TestPlugin 配置文件时出错: {str(e)}")
            self.enable = False
            self.allowed_contacts = []
            self.holiday_reminder = False
            self.holidays = []
            self.tianapi_key = ""
            self.use_holiday_api = False

    # 异步初始化
    async def async_init(self):
        return

    def check_holiday(self):
        """检查今天是否是节日，如果是则返回节日信息（本地配置）"""
        today = datetime.now()
        current_month = today.month
        current_day = today.day
        
        for holiday in self.holidays:
            if holiday["month"] == current_month and holiday["day"] == current_day:
                return {
                    "name": holiday["name"],
                    "greeting": holiday["greeting"]
                }
        return None

    async def get_holiday_from_api(self):
        """从天聚数行API获取今天的节日信息"""
        if not self.tianapi_key:
            return None
            
        today = datetime.now().strftime("%Y-%m-%d")
        try:
            url = f"https://apis.tianapi.com/jiejiari/index?key={self.tianapi_key}&date={today}&type=0&mode=1"
            async with aiohttp.request("GET", url, timeout=aiohttp.ClientTimeout(total=20)) as req:
                if req.status != 200:
                    return None
                    
                resp = await req.json()
                if resp.get("code") != 200:
                    return None
                    
                result = resp.get("result")
                if not result:
                    return None
                    
                # 从API中提取节日信息
                if "name" in result and result["name"]:
                    return {
                        "name": result["name"],
                        "greeting": f"祝您{result['name']}快乐！"
                    }
                # 检查是否有其他非官方节日 (mode=1时返回)
                festival_info = ""
                for festival in result.get("festivalsolar", []):
                    if festival_info:
                        festival_info += "、"
                    festival_info += festival["name"]
                
                for festival in result.get("festivallunar", []):
                    if festival_info:
                        festival_info += "、"
                    festival_info += festival["name"]
                
                if festival_info:
                    return {
                        "name": festival_info,
                        "greeting": f"今天是{festival_info}，祝您节日快乐！"
                    }
                    
        except Exception as e:
            logger.error(f"获取节日API失败: {e}")
        return None

    @on_pat_message
    async def handle_pat(self, bot: WechatAPIClient, message: dict):
        if not self.enable:
            return
        logger.info("测试插件：收到了拍一拍消息")
        await self.send_greeting_message(bot)

    @schedule('cron', hour=8, minute=30)
    async def daily_task(self, bot: WechatAPIClient):
        logger.info("TestPlugin 定时任务开始执行")
        if not self.enable:
            logger.info("TestPlugin 插件未启用，跳过任务")
            return
        
        await self.send_greeting_message(bot)

    async def send_greeting_message(self, bot: WechatAPIClient):
        """发送问候消息到个人用户（非群聊）"""
        try:
            id_list = []
            wx_seq, chatroom_seq = 0, 0
            logger.info("开始获取联系人列表")
            while True:
                try:
                    contact_list = await bot.get_contract_list(wx_seq, chatroom_seq)
                    id_list.extend(contact_list["ContactUsernameList"])
                    wx_seq = contact_list["CurrentWxcontactSeq"]
                    chatroom_seq = contact_list["CurrentChatRoomContactSeq"]
                    logger.info(f"已获取 {len(contact_list['ContactUsernameList'])} 个联系人，当前总数: {len(id_list)}")
                    if contact_list["CountinueFlag"] != 1:
                        break
                except Exception as e:
                    logger.error(f"获取联系人列表出错: {str(e)}")
                    break

            # 根据配置过滤联系人，排除群聊
            target_contacts = []
            if self.allowed_contacts:
                # 只选择配置中允许的联系人，且不是群聊的
                for contact_id in id_list:
                    if contact_id in self.allowed_contacts and not contact_id.endswith("@chatroom"):
                        target_contacts.append(contact_id)
                logger.info(f"根据配置，过滤出 {len(target_contacts)}/{len(id_list)} 个允许的非群聊联系人")
            else:
                # 如果配置为空，只选择非群聊联系人
                for contact_id in id_list:
                    if not contact_id.endswith("@chatroom"):
                        target_contacts.append(contact_id)
                logger.info(f"配置为空，默认选择所有非群聊联系人，共 {len(target_contacts)} 个")
            
            # 获取历史上的今天
            history_today = "无"
            try:
                logger.info("开始请求历史上的今天API")
                async with aiohttp.request("GET", "http://zj.v.api.aa1.cn/api/bk/?num=1&type=json",
                                        timeout=aiohttp.ClientTimeout(total=20)) as req:
                    logger.info(f"API响应状态码: {req.status}")
                    resp = await req.json()
                    logger.info(f"API响应内容: {resp}")
                    if resp.get("content"):
                        history_today = str(resp.get("content")[0])
                        logger.info(f"获取到历史上的今天: {history_today}")
                    else:
                        logger.warning("未在API响应中找到'content'字段")
            except asyncio.TimeoutError:
                logger.error("请求历史上的今天API超时")
                history_today = "🛜网络超时😭"
            except Exception as e:
                logger.error(f"请求历史上的今天API出错: {str(e)}")
                history_today = f"请求出错: {str(e)}"

            weekend = ["一", "二", "三", "四", "五", "六", "日"]
            current_day = datetime.now()
            weekday = weekend[current_day.weekday()]
            date_str = current_day.strftime('%Y年%m月%d号')
            logger.info(f"日期信息: {date_str}, 星期{weekday}")
            
            # 基础消息内容
            message = ("----- TestBot -----\n"
                    f"[Sun]早上好！今天是 {date_str}，星期{weekday}。\n"
                    "\n"
                    "📖历史上的今天：\n"
                    f"{history_today}")
            
            # 检查今天是否有节日
            holiday = None
            if self.holiday_reminder:
                # 优先使用API获取节日信息
                if self.use_holiday_api:
                    holiday = await self.get_holiday_from_api()
                    
                # 如果API没有获取到，或者不使用API，则使用本地配置
                if not holiday:
                    holiday = self.check_holiday()
                    
                # 如果有节日，添加节日提醒
                if holiday:
                    holiday_message = f"\n\n🎉今天是【{holiday['name']}】\n{holiday['greeting']}"
                    message += holiday_message

            logger.info(f"生成的消息内容: {message}")

            send_count = 0
            for contact in target_contacts:
                try:
                    logger.info(f"尝试向联系人 {contact} 发送消息")
                    await bot.send_text_message(contact, message)
                    send_count += 1
                    logger.info(f"成功发送消息到联系人 {contact}，总计发送: {send_count}/{len(target_contacts)}")
                    
                    sleep_time = randint(1, 3)
                    logger.info(f"等待 {sleep_time} 秒后继续发送")
                    await asyncio.sleep(sleep_time)
                except Exception as e:
                    logger.error(f"向联系人 {contact} 发送消息失败: {str(e)}")
            
            logger.info(f"TestPlugin 任务完成，成功发送给 {send_count} 个联系人")
        except Exception as e:
            logger.error(f"TestPlugin 任务执行过程中发生错误: {str(e)}")



